<template>
  <el-dialog
    :model-value="props.visible"
    title="设置角色权限对话框"
    width="90%"
    :lock-scroll="false"
    :close-on-click-modal="false"
    :before-close="closeDialog"
    @open="openDialogHandler"
  >
    <div style="min-height: 50vh">
      <div class="infoBar">
        <div class="title">当前角色信息</div>
        <div class="form">
          <div class="infoItem">
            <div class="label">角色编码 :</div>
            <div class="value">{{ roleName }}</div>
          </div>

          <div class="infoItem">
            <div class="label">角色描述 :</div>
            <div class="value">{{ roleDescription }}</div>
          </div>

          <div class="infoItem">
            <div class="label">角色名称 :</div>
            <div class="value">{{ roleRealName }}</div>
          </div>

          <div class="infoItem">
            <div class="label">角色分类 :</div>
            <div class="value">{{ getDescriptionStr(parentSortIds) }}</div>
          </div>
        </div>
      </div>

      <TableCard operation-bar-label="批量管理角色权限">
        <template #operationBar>
          <el-popconfirm
            title="确认批量删除角色权限？"
            placement="right"
            @confirm="setRolePermissions('remove', multipleDeleteItems)"
          >
            <template #reference>
              <el-button v-once-click color="#F56C6C" plain size="small">
                批量删除权限
              </el-button>
            </template>
          </el-popconfirm>
        </template>

        <template #table>
          <el-table
            :data="rolePermissionsList"
            stripe
            size="small"
            style="width: 100%"
            max-height="300"
            @selection-change="deleteItemSelectionChange"
            :headerCellStyle="tableHeaderCellStyle"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column property="name" label="Name" width="160" />
            <el-table-column property="code" label="Code" width="260" />
            <el-table-column property="enable" label="Enable" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.enable === 1" type="danger">
                  禁用
                </el-tag>
                <el-tag v-if="scope.row.enable === 0" type="success">
                  启用
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              property="description"
              label="Description"
              min-width="260"
            />
            <el-table-column label="Operation" width="100" fixed="right">
              <template #default="scope">
                <el-popconfirm
                  title="确认删除角色权限？"
                  placement="right"
                  @confirm="setRolePermissions('remove', [scope.row.id])"
                >
                  <template #reference>
                    <el-button v-once-click color="#F56C6C" plain size="small">
                      删除权限
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </TableCard>

      <br />

      <TableCard operation-bar-label="批量设置角色权限">
        <template #topBar>
          <div class="inputForm">
            <div class="inputItem">
              <div class="label">条件查询权限</div>
              <div class="value">
                <el-cascader
                  v-model="queryPermissionSortId"
                  :options="sortTypeTree"
                  :props="{ checkStrictly: true }"
                  placeholder="请选择上级分类（可选）"
                  @visible-change="selectVisibleChangeHandler"
                  size="large"
                  style="width: 100%"
                />
              </div>
            </div>

            <div class="buttonItem">
              <div class="label">操作</div>

              <el-button
                style="height: 100%"
                v-once-click
                color="#626aef"
                :icon="Search"
                @click="getPermissionsList"
              >
                查询
              </el-button>

              <div style="width: 10px"></div>

              <el-pagination
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                :background="true"
                :total="permissionTotal"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                layout="total, sizes, prev, pager, next"
                @size-change="handlePageSizeChange"
                @current-change="handlePageNumChange"
              />
            </div>
          </div>
        </template>

        <template #operationBar>
          <el-button
            v-once-click
            color="#626aef"
            plain
            size="small"
            @click="setRolePermissions('add', multipleSelectionItems)"
          >
            添加
          </el-button>

          <el-popconfirm
            title="确认重置当前角色权限？"
            placement="right"
            @confirm="setRolePermissions('refresh', multipleSelectionItems)"
          >
            <template #reference>
              <el-button v-once-click type="info" size="small">
                重置
              </el-button>
            </template>
          </el-popconfirm>
        </template>

        <template #table>
          <el-table
            ref="multipleTableRef"
            :data="querPermissionList"
            stripe
            size="small"
            style="width: 100%"
            max-height="300"
            @selection-change="handleSelectionChange"
            :headerCellStyle="tableHeaderCellStyle"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column property="name" label="Name" width="160" />
            <el-table-column property="code" label="Code" width="260" />
            <el-table-column property="enable" label="Enable" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.enable === 1" type="danger">
                  禁用
                </el-tag>
                <el-tag v-if="scope.row.enable === 0" type="success">
                  启用
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              property="description"
              label="Description"
              min-width="260"
            />
            <el-table-column label="Operation" width="100" fixed="right">
              <template #default="scope">
                <!-- <el-tag  type="danger">
                  已添加
                </el-tag> -->
                <el-button
                  v-if="!hasPerimssion(scope.row.id)"
                  v-once-click
                  color="#626aef"
                  plain
                  size="small"
                  @click="setRolePermissions('add', [scope.row.id])"
                >
                  添加权限
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </TableCard>
    </div>

    <template #footer>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button color="#626aef" size="large" @click="closeDialog">
          关闭弹窗
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import { useSortTreeStore, useThemeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'
import {
  getRolePermissionsDetailApi,
  setRolePermissionsApi,
} from '@/request/api/rolePermissions'
import { getPermissionsListApi } from '@/request/api/permissions'

import TableCard from '@/components/TableCard/TableCard.vue'

const props = defineProps({
  roleInfo: { type: Object as () => RoleItf, default: {} },
  visible: { type: Boolean, default: false },
})

// 定义传递给父组件的方法
const emits = defineEmits(['closeDialogHandler'])
const closeDialog = () => emits('closeDialogHandler')

const { originData, sortTree } = storeToRefs(useSortTreeStore())
const { findParentValues, formattingSortData, getSortList, getDescriptionStr } =
  useSortTreeStore()

const { tableHeaderCellStyle } = useThemeStore()
const { openAlert } = useMessageAlertStore()

// 对话框显示时的回调
const openDialogHandler = () => {
  if (sortTree.value.length === 0) getSortList()

  const { name, realName, description, sortId } = props.roleInfo
  roleName.value = name
  roleRealName.value = realName
  roleDescription.value = description
  parentSortIds.value = findParentValues(sortTree.value, sortId)

  // 提取出条件查询的树形结构 和 初始化值
  selectVisibleChangeHandler(true)
  queryPermissionSortId.value = [parentSortIds.value[0]]

  getPermissionsList()
  getRolePermissionsDetail()
}

// 角色上级分类id列表
const parentSortIds = ref<string[]>([])
const roleName = ref<string>('')
const roleRealName = ref<string>('')
const roleDescription = ref<string>('')

// 经过筛选后的分类树形列表
const sortTypeTree = ref<SortTreeItf[]>([])
// 下拉框显示回调函数
const selectVisibleChangeHandler = (visible: boolean) => {
  if (!visible) return
  const l = formattingSortData(originData.value, null, 'permission')
  const a = l.find((item) => item.value === parentSortIds.value[0])
  sortTypeTree.value = [a]
}

// 多选权限删除选项
const multipleDeleteItems = ref<string[]>([])
const deleteItemSelectionChange = (val: PermissionItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleDeleteItems.value = ids
}

// 角色权限列表
const rolePermissionsList = ref<PermissionItf[]>([])
// 获取角色权限详情
const getRolePermissionsDetail = async () => {
  const res = await getRolePermissionsDetailApi(props.roleInfo.id)
  if (res.code !== 200) return openAlert.error(res.message)
  rolePermissionsList.value = res.data.permissionsList
}

// 判断角色是否已经拥有某个权限
const hasPerimssion = (id: string): boolean => {
  return rolePermissionsList.value.some((item) => item.id === id)
}

// 分页查询相关
const permissionTotal = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getPermissionsList()
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getPermissionsList()
}

// 权限分类id，包含所有上级分类id
const queryPermissionSortId = ref<string[]>([])
// 查询到的权限列表
const querPermissionList = ref<PermissionItf[]>([])

// 获取权限列表
const getPermissionsList = async () => {
  let sortId = ''
  const q = queryPermissionSortId.value
  if (q && q.length > 0) sortId = q[q.length - 1]

  const res = await getPermissionsListApi(pageNum.value, pageSize.value, sortId)
  if (res.code !== 200) return openAlert.error(res.message)
  querPermissionList.value = res.data.records
  permissionTotal.value = res.data.total
}

// 多选表格对象
const multipleTableRef = ref<any>()
// 多选权限选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: PermissionItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 为角色设置权限
const setRolePermissions = async (
  type: 'refresh' | 'add' | 'remove',
  ids: string[]
) => {
  const res = await setRolePermissionsApi(props.roleInfo.id, type, ids)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('角色设置权限成功！')
  getRolePermissionsDetail()
  multipleTableRef.value!.clearSelection()
}
</script>

<style lang="less" scoped>
.infoBar {
  padding: 10px;

  > .title {
    font-size: 14px;
    font-weight: bold;
    user-select: none;
    color: #606266;
    letter-spacing: 2px;
    padding-bottom: 5px;
  }

  > .form {
    display: flex;
    flex-wrap: wrap;

    > .infoItem {
      display: flex;
      align-items: center;
      min-width: 400px;
      padding: 5px 0;

      > .label {
        font-size: 14px;
        font-weight: bold;
        padding-right: 15px;
        user-select: none;
        color: #918f8f;
        letter-spacing: 2px;
        width: 80px;
      }

      > .value {
        font-size: 14px;
        font-weight: bold;
        color: #606266;
        letter-spacing: 1px;
      }
    }
  }
}

.inputForm {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  > .inputItem {
    height: 40px;
    width: 500px;
    display: flex;
    align-items: center;
    margin-right: 15px;
    margin-bottom: 5px;
    // background-color: #cfcdcd21;

    > .label {
      min-width: 120px;
      height: 100%;
      font-size: 15px;
      font-weight: bold;
      color: #606266;
      user-select: none;
      background-color: #c8e0e4;
      display: flex;
      justify-content: center;
      align-items: center;
      padding-left: 5px;
      padding-right: 5px;
    }

    > .value {
      flex: 1;
      display: flex;
      height: 100%;
      border-radius: 4px;
      box-shadow: 0 0 1px 1px #bdbdbd8a;
    }
  }

  > .buttonItem {
    height: 40px;
    display: flex;
    align-items: center;
    padding-right: 10px;
    margin-right: 10px;
    margin-bottom: 5px;
    background-color: #cfcdcd21;

    > .label {
      min-width: 120px;
      height: 100%;
      font-size: 15px;
      font-weight: bold;
      color: #606266;
      user-select: none;
      background-color: #c8e0e4;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
      padding-left: 5px;
      padding-right: 5px;
    }
  }
}
</style>
